package service

import (
	"fmt"
	"ginim/utils"
	"github.com/gin-gonic/gin"
	"golang.org/x/exp/rand"
	"io"
	"os"
	"strings"
	"time"
)

func Upload(ctx *gin.Context) {
	writer := ctx.Writer
	request := ctx.Request
	fileSource, fileHead, err := request.FormFile("file")
	if err != nil {
		utils.ResponseFailure(writer, err.Error())
	}

	suffix := ".png"
	fileName := fileHead.Filename
	nameArr := strings.Split(fileName, ".")
	if len(nameArr) > 1 {
		suffix = "." + nameArr[len(nameArr)-1]
	}

	saveFileName := fmt.Sprintf("%d%04d%s", time.Now().Unix(), rand.Int31(), suffix)
	fileObj, err1 := os.Create("./web/asset/upload/" + saveFileName)
	if err1 != nil {
		utils.ResponseFailure(writer, err1.Error())
	}

	_, err2 := io.Copy(fileObj, fileSource)
	if err2 != nil {
		utils.ResponseFailure(writer, err2.Error())
	}

	url := "./asset/upload/" + saveFileName
	utils.ResponseSuccess(writer, url, "图片发送成功")
}
